import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

import vuexPersist from "vuex-persist";
import axios from "axios";

export default new Vuex.Store({
  state: {
    msg: "vuex中的公共数据msg",
    num: 10,
    list: [
      { name: "小明", r: "敲代码", num: 3 },
      { name: "周瑜", r: "放大火", num: 5 },
      { name: "王昭君", r: "砸冰块", num: 6 },
      { name: "钟馗", r: "钩子", num: 8 },
      { name: "干将莫邪", r: "放闪电", num: 10 },
      { name: "武则天", r: "放水", num: 5 },
      { name: "嬴政", r: "放剑", num: 6 },
    ],
    data: [],
  },
  mutations: {
    aa(state) {
      state.num++;
    },
    adds(state, obj) {
      state.list.push(obj);
    },
    remove(state, i) {
      state.list.splice(i, 1);
    },

    setdata(state, val) {
      state.data = val;
    },
    //给data赋上请求到的数据val
  },
  actions: {
    getdata(context) {
      // context是上下文环境的意思 可以理解为整个仓库
      axios.get("data.json").then((res) => {
        console.log(res);
        context.commit("setdata", res.data.list);
        //action可以请求异步请求，但是他没有权利操作state，还得调用mutation操作state
      });
    },
  },
  modules: {},
  getters: {
    all(state) {
      let num = 0;
      state.list.forEach((item) => {
        num += item.num;
      });
      return num;
    },
  },

  plugins: [
    new vuexPersist({
      storage: window.localStorage,
    }).plugin,
  ],
  //插件 配置持久化插件
});
//vuex共有五大核心
// state 状态 就是数据的意思 可以理解为之前的data

// mutation 用来操作数据state的 只有mutation才能操作state
